package com.immortal.module.security.userDetail;

import com.immortal.core.module.integration.IntegrationAuthentication;
import com.immortal.core.module.integration.IntegrationAuthenticationContext;
import com.immortal.core.module.integration.authenticator.IntegrationAuthenticator;
import com.immortal.module.security.SecUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;

@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    private List<IntegrationAuthenticator> authenticators;


    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        //判断是否是集成登录
        if (integrationAuthentication == null) {
            integrationAuthentication = new IntegrationAuthentication();
        }
        integrationAuthentication.setUsername(username);
        SecUser sysImUserAuthentication = this.authenticate(integrationAuthentication);
        setAuthorize(sysImUserAuthentication);
        return sysImUserAuthentication;
    }

    /**
     * 设置授权信息
     *
     * @param imUser
     */
    public void setAuthorize(SecUser imUser) {
    }

    private SecUser authenticate(IntegrationAuthentication integrationAuthentication) {
        if (this.authenticators != null) {
            for (IntegrationAuthenticator authenticator : authenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    return (SecUser) authenticator.authenticate(integrationAuthentication);
                }
            }
        }else {
            throw new InternalAuthenticationServiceException("缺少认证模块");
        }
        return null;
    }
}
